

#include "../include/muduo/net/TcpServer.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/TcpConnection.h"
#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateServer
{

public:
    TranslateServer(int port)
        : _server(&_baceloop, muduo::net::InetAddress("0.0.0.0", port), "TranslateServer", muduo::net::TcpServer::kNoReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void Start()
    {
        _server.start();
        _baceloop.loop();
    }


   

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
     {
        if(conn->connected() == true)
        {
            std::cout << "链接成功"<<std::endl;

        }
        else
        {
            std::cout << "链接失败" << std::endl;
        }
     }

    std::string translate(const std::string& str)
    {
        static::std::unordered_map<std::string,std::string> hash = 
        {
            {"hello","你好"},
            
             {"who","谁"},
             {"what","谁"},
             {"why","为什么"},
             {"eat","吃"}
        };
        auto it = hash.find(str);
        if(it == hash.end())
        {
            return "没听懂";
        }
        return it->second;
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::string str = buf->retrieveAllAsString();
        std::string resp = translate(str);
        conn->send(resp);

    }
    muduo::net::EventLoop _baceloop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer Server(8085);
    Server.Start();
    return 0;
}
